<?php

namespace app\user\controller;

class Bbs extends base
{
//前置方法
    protected $beforeActionList = [
        'map' => ['only' => 'index'],
    ];

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();

            if (isset($data['status']) || !empty($data['status'])) {
                $this->datas ['status'] = $data['status'];
            }

            if (!empty($data['title'])) {
                $this->datas ['title'] = ['like', '%' . $data['title'] . '%'];
            }
        }
        $this->datas ['uid'] = $this->getLoginUser()->id;
    }

    public function index()
    {
        $list = $this->model->page_index($this->datas, 'id deSC')
            ->appends($this->request->param());
        foreach ($list as $k=>$v){
            $list[$k]['num'] = db('bbsmass')->where('status',1)->where('fid',$v['id'])->count();
        }

        $this->assign([
            'list' => $list,
            'num' => $this->model->where($this->datas)->count(),
        ]);
        return $this->fetch();
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $data['status'] = '1';
            $data = $this->request->post();
            $data['uid'] = $this->getLoginUser()->id;
            $data['username'] = $this->getLoginUser()->name;

            if (!empty($data['id'])) {
//                $data['status'] = '0';
                $data['error'] = null;
                return $this->update($data);
            }
            $data['lang']=cookie('think_var');

            $result = $this->model->allowField(true)->save($data);
            if ($result) {
                $this->success('发布话题成功！');
                return ajax_info(lang('Submit successfully awaiting review'), 'y');

            }
            $this->error('发布话题失败！');
            return ajax_info(lang('Submission Failed'));

        }
        $data = $this->model->where('id', $this->request->param('id'))->where('uid', $this->getLoginUser()->id)->find();
        $this->assign(['data' => $data]);
        return $this->fetch();
    }

    public function read($id){
        $datas['status']=1;
        $datas['fid']=$id;
        $list = model('bbsmass')->page_index($datas, 'id ASC')
            ->appends($this->request->param());


        $this->assign([
            'list' => $list,
            'num' => model('bbsmass')->where($datas)->count(),
        ]);
        $this->assign('list',$list);
        return $this->fetch();
    }

}
